/*
通过 mutation 间接更新 state 的多个方法的对象
*/
// 接口函数
import {
  reqCompositeIndexNow,
  reqCompositeIndexHistory,
  reqEvent, // 查询报警事件
  reqServiceStatistic, // 获取加油区或商超区 服务人数和服务时间
  reqCustomerEnter, // 获取商超进店人次
  reqViolateNow, // 获取实时违规率
  reqViolateHistory, // 获取历史违规率
  reqManagerOnlineHistory, // 获取历史站长在站率
  reqStatistic, // 事件统计 strict 版本，可用来统计违规事件数
  reqCIHistory, // 获取拥堵指数
  reqRefuelServiceNow, // 获取加油岛实时服务时间
  reqRefuelServiceHistory, // 获取加油岛历史服务时间
  reqStreamQuery, // 获取站点视频流地址
  reqStreamPull // 请求服务器开始推流
} from "@/api"

import dayjs from 'dayjs'
import constData from "@/util/constData"
import {mapTimeList} from '../util/util'

export default {
  // 获取实时的四项评分
  async getNowFourScore({commit}, params) {
    let fourScore = []
    let resData = await reqCompositeIndexNow(params)
    let details = resData.data.details
    Object.keys(details).forEach((item, index) => {
      switch (item) {
        case "safety":
          fourScore.push({
            name: '安全',
            en: 'safety',
            value: 0,
            score: details["safety"]
          })
          break
        case "efficiency":
          fourScore.push({
            name: '效率',
            en: 'efficiency',
            value: 0,
            score: details["efficiency"]
          })
          break
        case "management":
          fourScore.push({
            name: '管理',
            en: 'management',
            value: 0,
            score: details["management"]
          })
          break
        case "service":
          fourScore.push({
            name: '服务',
            en: 'service',
            value: 0,
            score: details["service"]
          })
          break
      }
    })
    commit('GETNOWFOURSCORE', {fourScore})
  },

  // 获取综合评分变化趋势
  async getOverallScoreTrendData ({commit}, params) {
    let overallScoreData = []
    let fourItemScoreData = []
    let resData = await reqCompositeIndexHistory(params)
    let group = resData.data.group
    console.log('获取 主页综合评分变化趋势', resData, group)
    Object.keys(group).forEach((item, index) => {
      overallScoreData.push({
        value: Math.round(group[item]["score"]*100)/100,
        label: {
          show: index%2 === 1 ? true : false
        }
      })
      fourItemScoreData.push([item, Math.round(group[item]["details"]["service"]), "服务"])
      fourItemScoreData.push([item, Math.round(group[item]["details"]["safety"]), "安全"])
      fourItemScoreData.push([item, Math.round(group[item]["details"]["management"]), "管理"])
      fourItemScoreData.push([item, Math.round(group[item]["details"]["efficiency"]), "效率"])

    })
    commit('GETOVERALLSCORETRENDDATA', {overallScoreData, fourItemScoreData})
  },

  // 更新选择的站点数据
  updateSelectedStationData ({commit}, selectedData) {
    // console.log('更新选择的站点数据', selectedData)
    commit('UPDATESELECTEDSTATIONDATA', {selectedData})
  },

  // 初始化所有状态数据
  initAllStateData ({commit}) {
    commit('INITALLSTATEDATA')
  },

  // 获取商超区 服务人数和服务时间
  async getServiceStatistic({commit}, params) {
    let resData = await reqServiceStatistic(params)
    // console.log('获取商超区 服务人数和服务时间:', resData)
    if(resData.code === 9000) return
    let serviceGroupData = resData.data.count_group.group
    // 映射的时间列表
    let timeList = mapTimeList(params.start_time, params.end_time, params.group)

    // 处理返回的数据
    let getServiceData = {
      servicePersonsSum: 0, // 服务总人次
      serviceAllTime: 0, // 收银服务总时间，总值
      serviceArgTime: 0, // 收银服务时间，平均值
      servicePersonsData: [], // 服务人次
      avgServiceTimeData: [], // 平均收银服务时间
    }

    getServiceData.servicePersonsSum = resData.data.count_all
    getServiceData.serviceAllTime = resData.data.time_all
    getServiceData.serviceArgTime = Math.round(resData.data.count_group.average_time/60)
    getServiceData.servicePersonsData = timeList.map((time) => {
      return serviceGroupData[time] ? serviceGroupData[time].total_num : 0
    })
    getServiceData.avgServiceTimeData = timeList.map((time) => {
      return serviceGroupData[time] ? serviceGroupData[time].average_time : 0
    })
    // console.log('处理 商超区服务人数和服务时间 后的数据: ', getServiceData)

    commit('GETSERVICESTATISTIC', { getServiceData })
  },
  // 获取商超进店人次
  async getCustomerEnter({commit}, params) {
    let resData = await reqCustomerEnter(params)
    let customerEnterDataGroup = resData.data.count_group.group
    // console.log('获取进店人次：', resData)
    // 映射的时间列表
    let timeList = mapTimeList(params.start_time, params.end_time, params.group)

    // 处理返回的数据
    let getCustomerEnterData = {
      enterPersonsSum: 0, // 进店总人次
      enterPersonsData: [], // 进店人次分布
    }
    getCustomerEnterData.enterPersonsSum = Math.round(resData.data.count_all)
    getCustomerEnterData.enterPersonsData = timeList.map((time)=>{
      return customerEnterDataGroup[time] ? Math.round(customerEnterDataGroup[time]) : 0
    })
    // console.log('处理 进店人次 后的数据：', getCustomerEnterData)

    commit('GETCUSTOMERENTER', {getCustomerEnterData})
  },
  // 获取 实时违规率
  async getNowViolateRate({commit}, params) {
    let resData = await reqViolateNow(params)
    let getNowViolateRateData = resData.data[params.station]
    // console.log('获取实时违规率:', resData, getNowViolateRateData)

    let getViolateRateData = 0
    Object.keys(getNowViolateRateData).forEach((ele)=>{
      getViolateRateData = (getNowViolateRateData[ele] * 100).toFixed(2)
    })
    // console.log('处理 实时违规率 后的数据:', getViolateRateData)

    commit('GETNOWVIOLATERATE', {getViolateRateData})
  },

  // 获取 便利店和加油区历史 违规率
  async getHistoryViolateRate({commit}, params) {
    let resData = await reqViolateHistory(params)
    // let getViolateRateData = resData.data[params.station]
    // console.log('获取便利店和加油区历史 违规率:', resData)

    let getHistoryViolateRateData = 0
    // Object.keys(getViolateRateData).forEach((ele)=>{
    //   getHistoryViolateRateData += getViolateRateData[ele] * 100
    // })
    getHistoryViolateRateData = (resData.data.general*100).toFixed(2)
    // console.log('处理 便利店和加油区历史违规率 后的数据:', getHistoryViolateRateData)

    if(params.category === 'checkout') {
      commit('GETCHECHOUTHISTORYVIOLATERATE', {getHistoryViolateRateData})
    } else if(params.category === 'refuel') {
      commit('GETREFUELHISTORYVIOLATERATE', {getHistoryViolateRateData})
    }
  },

  // 获取站长在站率, 没有实时数据，只有周数据和月数据
  async getManagerOnlineRate({commit}, params) {
    let resData = await reqManagerOnlineHistory(params)
    let managerOnlineRateGroup = resData.data.group
    // console.log("获取站长在站率:", resData, managerOnlineRateGroup)
    // 映射的时间列表
    let timeList = mapTimeList(params.start_time, params.end_time, 'day')

    let getManagerOnlineRateData = {
      managerOnlineRateData: []
    }
    getManagerOnlineRateData.managerOnlineRateData = timeList.map((time)=>{
      return managerOnlineRateGroup[time] ? (managerOnlineRateGroup[time] * 100).toFixed(1) : 0
    })
    // console.log("处理 站长在站率 后的数据:", getManagerOnlineRateData)

    commit('GETMANAGERONLINERATE', {getManagerOnlineRateData})
  },

  // 获取 实时综合指数评分
  async getCompositeIndexNow({commit}, params) {
    let resData = await reqCompositeIndexNow(params)
    let scoreData = resData.data.details
    scoreData['overall'] = resData.data.general
    // console.log('获取 实时综合指数评分:', resData, scoreData)

    commit('GETCOMPOSITEINDEXNOW', {scoreData})
  },
  // 获取 站点评分变化趋势
  async getStationScoreTrendData ({commit}, params) {
    let resData = await reqCompositeIndexHistory(params)
    let stationScoreGroup = resData.data.group
    // console.log('获取 站点评分变化趋势:', resData, stationScoreGroup)
    // 映射的时间列表
    let timeList = mapTimeList(params.start_time, params.end_time, 'day')

    let stationScoreListData = {
      overall: [], // 总评分
      safety: [], // 安全评分
      efficiency: [], // 效率评分
      management: [], // 管理评分
      service: [], // 服务评分
      checkout: [], // 便利店
      refuel: [], // 加油区
      safebox: [], // 财务室
      unload: [] // 卸油口
    }

    let stationScoreData = {
      overall: 0, // 总评分
      safety: 0, // 安全评分
      efficiency: 0, // 效率评分
      management: 0, // 管理评分
      service: 0, // 服务评分
      checkout: 0, // 便利店
      refuel: 0, // 加油区
      safebox: 0, // 财务室
      unload: 0 // 卸油口
    }

    timeList.forEach((item, index) => {
      stationScoreListData.overall.push({
        value: Math.round(stationScoreGroup[item]["score"]*100)/100,
        label: {
          show: index%2 === 1 ? true : false
        }
      })
      stationScoreListData.service.push({
        value: Math.round(stationScoreGroup[item]["details"]["service"]*100)/100
      })
      stationScoreListData.safety.push({
        value: Math.round(stationScoreGroup[item]["details"]["safety"]*100)/100
      })
      stationScoreListData.management.push({
        value: Math.round(stationScoreGroup[item]["details"]["management"]*100)/100
      })
      stationScoreListData.efficiency.push({
        value: Math.round(stationScoreGroup[item]["details"]["efficiency"]*100)/100
      })
      stationScoreListData.checkout.push({
        value: Math.round(stationScoreGroup[item]["details"]["checkout"]*100)/100
      })
      stationScoreListData.refuel.push({
        value: Math.round(stationScoreGroup[item]["details"]["refuel"]*100)/100
      })
      stationScoreListData.safebox.push({
        value: Math.round(stationScoreGroup[item]["details"]["safebox"]*100)/100
      })
      stationScoreListData.unload.push({
        value: Math.round(stationScoreGroup[item]["details"]["unload"]*100)/100
      })

      stationScoreData.overall += stationScoreGroup[item]["score"]
      stationScoreData.service += stationScoreGroup[item]["details"]["service"]
      stationScoreData.safety += stationScoreGroup[item]["details"]["safety"]
      stationScoreData.management += stationScoreGroup[item]["details"]["management"]
      stationScoreData.efficiency += stationScoreGroup[item]["details"]["efficiency"]
      stationScoreData.checkout += stationScoreGroup[item]["details"]["checkout"]
      stationScoreData.refuel += stationScoreGroup[item]["details"]["refuel"]
      stationScoreData.safebox += stationScoreGroup[item]["details"]["safebox"]
      stationScoreData.unload += stationScoreGroup[item]["details"]["unload"]
    })

    stationScoreData.overall = stationScoreData.overall/timeList.length
    stationScoreData.service = stationScoreData.service/timeList.length
    stationScoreData.safety = stationScoreData.safety/timeList.length
    stationScoreData.management = stationScoreData.management/timeList.length
    stationScoreData.efficiency = stationScoreData.efficiency/timeList.length
    stationScoreData.checkout = stationScoreData.checkout/timeList.length
    stationScoreData.refuel = stationScoreData.refuel/timeList.length
    stationScoreData.safebox = stationScoreData.safebox/timeList.length
    stationScoreData.unload = stationScoreData.unload/timeList.length

    // console.log('处理 站点评分变化趋势 后的数据:', stationScoreListData, stationScoreData)

    commit('GETSTATIONSCORETRENDDATA', { stationScoreListData, stationScoreData })
  },

  // 获取加油区 服务车辆数和服务时间
  async getRefuelServiceStatistic({commit}, params) {
    let resData = await reqServiceStatistic(params)
    let serviceGroupData = resData.data.count_group.group
    // console.log('获取加油区 服务车辆数和服务时间：', resData)
    // 映射的时间列表
    let timeList = mapTimeList(params.start_time, params.end_time, params.group)

    // 处理返回的数据
    let getServiceData = {
      serviceCarsSum: 0, // 服务总车辆数
      serviceAllTime: 0, // 车辆服务总时间，总值
      serviceArgTime: 0, // 车辆服务平均时间，平均值
      serviceCarsData: [], // 服务车辆数
      avgServiceTimeData: [], // 平均车辆服务时间
    }

    getServiceData.serviceCarsSum = resData.data.count_all
    getServiceData.serviceAllTime = resData.data.time_all
    getServiceData.serviceArgTime = (resData.data.count_group.average_time/60).toFixed(2)
    getServiceData.serviceCarsData = timeList.map((time) => {
      return serviceGroupData[time] ? serviceGroupData[time].total_num : 0
    })
    getServiceData.avgServiceTimeData = timeList.map((time) => {
      return serviceGroupData[time] ? (serviceGroupData[time].average_time/60).toFixed(1) : 0
    })
    console.log('处理 加油区服务车辆数和平均服务时间 后的数据: ', getServiceData)

    commit('GETREFUELSERVICESTATISTIC', { getServiceData })
  },

  // 获取加油站违规事件数据
  async getViolateEventData ({commit}, params) {
    let resData = await reqStatistic(params)
    let violateEventData = resData.data.categorys;
    // console.log('获取加油站违规事件数据：', resData, violateEventData)

    let violateData = {
      checkoutSum: 0, // 便利店违规事件总数
      refuelSum: 0, // 加油区违规事件总数
      safeboxSum: 0, // 保险柜违规事件总数
      unloadSum: 0, // 卸油口违规事件总数
      checkoutVE: [], // 便利店违规事件
      refuelVE: [], // 加油区违规事件
      safeboxVE: [], // 保险柜违规事件
      unloadVE: [] // 卸油口违规事件
    }

    violateData.checkoutSum = violateEventData["checkout"].total_num;
    violateData.refuelSum = violateEventData["refuel_side"].total_num;
    violateData.safeboxSum = violateEventData["safebox"].total_num;
    violateData.unloadSum = violateEventData["unload"].total_num;

    let checkoutData = violateEventData["checkout"].group.group
    let refuel_sideData = violateEventData["refuel_side"].group.group
    let safeboxData = violateEventData["safebox"].group.group
    let unloadData = violateEventData["unload"].group.group

    // 映射的时间列表
    let timeList = mapTimeList(params.start_time, params.end_time, params.group)

    timeList.forEach((time)=>{
      violateData.checkoutVE.push(checkoutData[time]?checkoutData[time]:0)
      violateData.refuelVE.push(refuel_sideData[time]?refuel_sideData[time]:0)
      violateData.safeboxVE.push(safeboxData[time]?safeboxData[time]:0)
      violateData.unloadVE.push(unloadData[time]?unloadData[time]:0)
    })

    // console.log('处理 加油站违规事件数据 后的数据: ', violateData)

    commit('GETVIOLATEEVENTDATA', { violateData })
  },

  // 获取卸油次数，保险柜打开次数，钱箱打开次数
  async getStationCenterCountData ({commit}, params) {
    let resData = await reqStatistic(params)
    let actionsData = resData.data.actions;
    console.log('获取卸油次数，保险柜打开次数，钱箱打开次数：', resData, actionsData)

    let countData = {
      unloadCount: 0, // 卸油次数
      safeboxCount: 0, // 保险柜打开次数
      moneyboxCount: 0 // 钱箱打开次数
    }

    countData.safeboxCount = actionsData["开启保险柜"]["total_num"] // 保险柜
    countData.moneyboxCount = actionsData["开启钱箱"]["total_num"] // 钱箱
    countData.unloadCount = actionsData["油罐车到达"]["total_num"] // 卸油次数

    commit('GETSTATIONCENTERCOUNTDATA', { countData })
  },
  // 获取 加油区实时违规率
  async getRefuelNowViolateRate({commit}, params) {
    let resData = await reqViolateNow(params)
    // console.log('获取加油区实时违规率:', resData)

    let refuelViolateRateData = (resData.data.general * 100).toFixed(2)
    // console.log('处理 加油区实时违规率 后的数据:', refuelViolateRateData)

    commit('GETREFUELNOWVIOLATERATE', {refuelViolateRateData})
  },
  // 获取事件表格列表
  async getEventsTableData({commit}, params) {
    let resData = await reqStatistic(params)
    let actionsData = resData.data.actions;
    let actions = params.actions.split(',')
    // console.log('获取事件表格列表：', resData, actionsData, actions)

    let eventTableData = actions.map(event => {
      let todayCount = actionsData[event]["group"]["group"][dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss")];
      let yestodayCount = actionsData[event]["group"]["group"][params.start_time];
      let decreaseCount = "";
      if (yestodayCount - todayCount > 0) {
        decreaseCount = "下降 " + Math.abs(yestodayCount - todayCount) + " 次";
      } else if (yestodayCount - todayCount < 0) {
        decreaseCount = "上升 " + Math.abs(yestodayCount - todayCount) + " 次";
      } else {
        decreaseCount = "持平";
      }
      return {
        eventName: event,
        todayCount,
        yestodayCount,
        decreaseCount
      }
    })
    eventTableData = eventTableData.sort((a, b) => b.todayCount - a.todayCount);
    // console.log('处理 事件表格列表 后的数据:', eventTableData)

    commit('GETEVENTSTABLEDATA', {eventTableData})
  },

  // 获取拥堵指数
  async getJamIndexData ({commit}, params) {
    let resData = await reqCIHistory(params)
    let jamIndexData = resData.data[params.station].general
    // console.log('获取拥堵指数:', resData, jamIndexData)

    // 映射的时间列表
    let timeList = mapTimeList(params.start_time, params.end_time, params.group)
    let jamIndex = []
    jamIndex = timeList.map(time => {
      return {
        value: (jamIndexData[time] * 5).toFixed(2),
        symbolSize: (jamIndexData[time] * 5).toFixed(2) === '0.00' ? 4 : 10,
        label: {
          show: (jamIndexData[time] * 5).toFixed(2) === '0.00' ? false : true
        }
      }
    })

    // console.log('处理 拥堵指数 后的数据:', jamIndex)

    commit('GETJAMINDEXDATA', {jamIndex})
  },
  // 获取 实时加油岛服务时间
  async getNowRefuelServiceTimeData ({commit}, params) {
    let resData = await reqRefuelServiceNow(params)
    let nowRefuelTime = resData.data[params.station][dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss")]
    // console.log('获取 实时加油岛服务时间:', resData, nowRefuelTime)

    let refuelServiceName = [] // 加油岛名称
    let refuelServiceTime = [] // 加油岛对应服务时间

    Object.keys(nowRefuelTime).forEach((item, index) => {
      if(item !== 'general' ){
        refuelServiceName.push((index + 1) + '号')
        refuelServiceTime.push((nowRefuelTime[item]*24).toFixed(2))
      }
    })

    // console.log('处理 实时加油岛服务时间 后的数据:', refuelServiceName, refuelServiceTime)

    commit('GETNOWREFUELSERVICETIMEDATA', {refuelServiceName, refuelServiceTime})
  },
  // 获取 历史加油岛服务时间
  async getHistoryRefuelServiceTimeData ({commit}, params) {
    let resData = await reqRefuelServiceHistory(params)
    let refuelServiceTime = resData.data[params.station]
    // console.log('获取 历史加油岛服务时间:', resData, refuelServiceTime)

    let refuelServiceTimeData = {};
    Object.keys(refuelServiceTime).forEach((time) => {
      Object.keys(refuelServiceTime[time]).forEach((refuelIndex) => {
        if (isNaN(refuelServiceTimeData[refuelIndex])) refuelServiceTimeData[refuelIndex] = 0;
        refuelServiceTimeData[refuelIndex] += refuelServiceTime[time][refuelIndex]
      })
    })

    // console.log("refuelServiceTimeData：", refuelServiceTimeData);

    if('general' in refuelServiceTimeData) delete refuelServiceTimeData.general

    // console.log("refuelServiceTimeData：", refuelServiceTimeData);

    let refuelServiceIndexName = [] // 加油岛名称
    let refuelServiceIndexTime = [] // 加油岛对应服务时间

    Object.keys(refuelServiceTimeData).forEach((item, index) => {
      if(item !== 'general' ){
        refuelServiceIndexName.push((index + 1) + '号')
        refuelServiceIndexTime.push((refuelServiceTimeData[item]*24).toFixed(2))
      }
    })

    // console.log('处理 历史加油岛服务时间 后的数据:', refuelServiceIndexName, refuelServiceIndexTime)

    commit('GETHISTORYREFUELSERVICETIMEDATA', {refuelServiceIndexName, refuelServiceIndexTime})
  },

  // 获取站点视频流地址
  async getStationVideoStreamUrl({commit}, params) {
    let resData = await reqStreamQuery(params)

    console.log('获取 站点视频流地址:',params, resData)
    if(resData.code === 6000) {
      let videoList = resData.data
      videoList.forEach(ele => {
        ele['title'] = constData.stationList2[ele.station] + constData.categoryData2[ele.category] + ele.channel + '号视频'
      })
      // videoList = videoList.sort((a, b) => Number(b.channel)-Number(a.channel))
      // console.log('处理 站点视频流地址:',videoList)

      commit('GETSTATIONVIDEOSTREAMURL', { videoList })
    }else{
      // 获取失败后更新获取的视频流状态，页面提示用户这个站点的流不可用
      commit('CHANGEGETVEDIOSTREAMSTATE404')
    }
  },
  // 更新 站点视频流 推流状态
  async updateStationVideoStreamState({commit}, params) {
    let resData = await reqStreamQuery(params)

    // console.log('更新 站点视频流 推流状态:',resData)
    if(resData.code === 6000) {
      let videoList = resData.data
      // console.log('处理 站点视频流 推流状态:',videoList)

      commit('UPDATESTATIONVIDEOSTREAMSTATE', { videoList })
    }
  },
  // 更新 站点视频流 请求状态， 从 404 到 200
  updateGetStationVideoStreamState200({commit}) {
    commit('CHANGEGETVEDIOSTREAMSTATE200')
  },
  // 加载视频流实时播放页面
  async onloadVideoStreamPlayer ({commit}, params) {
    let resData = await reqStreamPull(params)
    // console.log('请求到的推流信息：', resData)
    if(resData.code === 6000) {
      let reqPlayerInfo = resData.data
      reqPlayerInfo['title'] = constData.stationList2[reqPlayerInfo.station] + constData.categoryData2[reqPlayerInfo.category] + reqPlayerInfo.channel + '号视频'

      commit('ONLOADVIDEOSTREAMPLAYER', { reqPlayerInfo })
    }
  },
  // 关闭视频流详情页，打开视频流网格页面
  closeDetailsLoadVideoGridPages ({commit}) {
    commit('CLOSEDETAILSLOADVIDEOGRIDPAGES')
  },
  // 获取 实时监控页面 事件列表
  async getMonitorEventsTableList ({commit}, params) {
    let resData = await reqEvent(params)
    let monitorEventsData = resData.data.events;

    commit('GETMONITOREVENTSTABLELIST', {monitorEventsData})
  },
  // 更新报警事件查询的表单数据
  updateEventsQueryFormData ({commit}, newFormData)  {
    console.log('参数：', newFormData)
    commit('UPDATEEVENTSQUERYFORMDATA', {newFormData})
  }
}
